<template>
    <div class="home">
        <div class="search-container">
            <el-form :inline="true" :model="queryParams" size="mini" class="demo-form-inline">
                <el-form-item label="物品名称">
                    <el-input v-model="queryParams.name" placeholder="物品名称"></el-input>
                </el-form-item>
                <el-form-item label="时间范围">
                    <el-date-picker
                            v-model="queryParams.timeRange"
                            type="daterange"
                            align="right"
                            unlink-panels
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">查询</el-button>
                    <el-button @click="handleNewItem"
                               size="mini"
                               type="success">数据录入
                    </el-button>
                </el-form-item>
            </el-form>
        </div>

        <div style="padding:20px;" class="table-content">
            <el-table :data="tableData"
                      stripe
                      highlight-current-row
                      style="width: 100%">
                <el-table-column label="名称">
                    <template slot-scope="scope">
                        <el-link :data-clipboard-text="scope.row.name" class="btn" type="primary">{{scope.row.name}}
                        </el-link>
                    </template>
                </el-table-column>

                <el-table-column label="市场最高价"
                                 prop="priceTop">
                    <template slot-scope="scope">
                        <span style="color: orangered;">{{scope.row.priceTop | moneyFormat}}</span>
                    </template>
                </el-table-column>

                <el-table-column label="市场最低价"
                                 prop="priceBottom">
                    <template slot-scope="scope">
                        <span style="color: forestgreen;">{{scope.row.priceBottom | moneyFormat}}</span>
                    </template>
                </el-table-column>

                <el-table-column label="市场平均价">
                    <template slot-scope="scope">
                        <span>{{scope.row.averagePrice | moneyFormat}}</span>
                    </template>
                </el-table-column>

                <el-table-column label="蓝图价格">
                    <template slot-scope="scope">
                        <span>{{scope.row.bluePrice | moneyFormat}}</span>
                    </template>
                </el-table-column>

                <el-table-column label="矿物总价格">
                    <template slot-scope="scope">
                        <span>{{scope.row.material | moneyFormat}}</span>
                    </template>
                </el-table-column>

                <el-table-column label="总物料成本">
                    <template slot-scope="scope">
                        <span>{{scope.row.cost | moneyFormat}}</span>
                    </template>
                </el-table-column>

                <el-table-column label="利润">
                    <template slot-scope="scope">
                        <span v-if="scope.row.profit >= 0"
                              style="color: forestgreen">{{scope.row.profit | moneyFormat}}</span>
                        <span v-else style="color: orangered">{{scope.row.profit | moneyFormat}}</span>
                    </template>
                </el-table-column>

                <el-table-column label="创建时间">
                    <template slot-scope="scope">
                        {{scope.row.createTime | dateFormat}}
                    </template>
                </el-table-column>

                <el-table-column label="修改时间">
                    <template slot-scope="scope">
                        {{scope.row.updateTime | dateFormat}}
                    </template>
                </el-table-column>

                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button @click="handleEdit(scope.$index, scope.row)" type="primary" size="mini"
                                   icon="el-icon-edit" circle>
                        </el-button>
                        <el-button @click="handleDelete(scope.$index, scope.row)" type="danger" size="mini"
                                   icon="el-icon-delete" circle>
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

        </div>
        <!-- 新增数据 -->
        <el-drawer title="数据录入"
                   :visible.sync="show"
                   @open="bindEnter"
                   direction="ltr">
            <div style="padding: 20px;">
                <el-form ref="form"
                         size="mini"
                         :model="form"
                         label-width="120px">

                    <el-form-item label="名称">
                        <el-input v-model="form.name"></el-input>
                    </el-form-item>

                    <el-form-item label="市场最高价">
                        <el-col :span="span10">
                            <el-input v-model.number="form.priceTop" placeholder="$"></el-input>
                        </el-col>
                        <el-col :span="span7">
                            {{ form.priceTop | moneyFormat }}
                        </el-col>
                    </el-form-item>

                    <el-form-item label="市场最低价">
                        <el-col :span="span10">
                            <el-input v-model.number="form.priceBottom" placeholder="$"></el-input>
                        </el-col>
                        <el-col :span="span7">
                            {{ form.priceBottom | moneyFormat }}
                        </el-col>
                    </el-form-item>

                    <el-form-item label="市场平均价">
                        <el-col :span="span7">
                            <el-input v-model.number="form.priceAverage.a" placeholder="价格1"></el-input>
                        </el-col>
                        <el-col :span="span7">
                            <el-input v-model.number="form.priceAverage.b" placeholder="价格2"></el-input>
                        </el-col>
                        <el-col :span="span7">
                            <el-input v-model.number="form.priceAverage.c" placeholder="价格3"></el-input>
                        </el-col>
                    </el-form-item>
                    <el-form-item label="市场平均价">
                        <span>{{priceAverageRes | moneyFormat}}</span>
                    </el-form-item>

                    <el-form-item label="蓝图价格">
                        <el-col :span="span10">
                            <el-input v-model.number="form.bluePrice" placeholder="$"></el-input>
                        </el-col>
                        <el-col :span="span7">
                            {{ form.bluePrice | moneyFormat }}
                        </el-col>
                    </el-form-item>

                    <el-form-item label="品级">
                        <el-radio-group v-model="form.level">
                            <el-radio-button :label="1">R1</el-radio-button>
                            <el-radio-button :label="2">R2</el-radio-button>
                            <el-radio-button :label="3">R3</el-radio-button>
                            <el-radio-button :label="4">R4</el-radio-button>
                            <el-radio-button :label="5">R5</el-radio-button>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="科技等级">
                        <el-radio-group v-model="form.tLevel">
                            <el-radio-button :label="1">T1</el-radio-button>
                            <el-radio-button :label="2">T2</el-radio-button>
                            <el-radio-button :label="3">T3</el-radio-button>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="半导体">
                        <el-col :span="span10">
                            <el-input v-model.number="form.a" placeholder="$"></el-input>
                        </el-col>
                        <el-col :span="span7">
                            {{ form.a | moneyFormat }}
                        </el-col>
                    </el-form-item>

                    <el-form-item label="碳氢聚合物">
                        <el-col :span="span10">
                            <el-input v-model.number="form.b" placeholder="$"></el-input>
                        </el-col>
                        <el-col :span="span7">
                            {{ form.b | moneyFormat }}
                        </el-col>
                    </el-form-item>

                    <el-form-item label="超导陶瓷体">
                        <el-col :span="span10">
                            <el-input v-model.number="form.c" placeholder="$"></el-input>
                        </el-col>
                        <el-col :span="span7">
                            {{ form.c | moneyFormat }}
                        </el-col>
                    </el-form-item>

                    <el-form-item label="氧化物晶体">
                        <el-col :span="span10">
                            <el-input v-model.number="form.d" placeholder="$"></el-input>
                        </el-col>
                        <el-col :span="span7">
                            {{ form.d | moneyFormat }}
                        </el-col>
                    </el-form-item>

                    <el-form-item label="铱钛合金">
                        <el-col :span="span10">
                            <el-input v-model.number="form.e" placeholder="$"></el-input>
                        </el-col>
                        <el-col :span="span7">
                            {{ form.e | moneyFormat }}
                        </el-col>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="success"
                                   @click="onSubmit">录入
                        </el-button>

                        <el-button type="primary"
                                   @click="handleMockData">假数据
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-drawer>

        <div>
            <input style="width:3px;" type="text" ref="copy" :value="copy">
        </div>
    </div>
</template>

<script>
  import Clipboard from 'clipboard'

  const span10 = 10
  const span7 = 7
  // 材料单价
  const mine = {
    a: 5,
    b: 20,
    c: 80,
    d: 120,
    e: 1280
  }
  // 时间范围
  const pickerOptions = {
    shortcuts: [{
      text: '最近一周',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        picker.$emit('pick', [start, end]);
      }
    }, {
      text: '最近一个月',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        picker.$emit('pick', [start, end]);
      }
    }, {
      text: '最近三个月',
      onClick(picker) {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        picker.$emit('pick', [start, end]);
      }
    }]
  }

  const TAX = 0.05 // 税率
  const MINE_TRANSFER = 3 // 因为联盟币换成矿物可以通过物流任务扩大三倍
  export default {
    name: 'home',
    created() {
      if (window.localStorage.prices) {
        this.tableData = JSON.parse(window.localStorage.prices)
      }
    },
    mounted() {
      this.bindShortCuts() // 绑定键盘快捷键
      this.bindClip()
    },
    data() {
      return {
        span10: 10,
        span7: 7,
        copy: '',
        queryParams: {
          name: '',
          timeRange: '', // 时间范围
          startTime: '',
          endTime: ''
        },
        pickerOptions, // 时间选择器快捷选项
        tableData: [],
        itemExample: { // tableData里数据的格式，仅仅作为示例
          name: '', // 名字
          priceTop: '', // 市场最高价格
          priceBottom: '', // 市场最低价
          priceAverage: '', // 市场平均价
          bluePrice: '',
          material: '', // 材料价格
          cost: '', // 总物料成本
          profit: '', // 利润
          createTime: '', // 创建时间
          updateTime: '' // 修改时间
        },
        form: {
          name: '',
          priceTop: '', // 市场最高价格
          priceBottom: '', // 市场最低价
          level: 1, // 品级
          tLevel: 1, //
          priceAverage: { // 市场平均价格
            a: '',
            b: '',
            c: ''
          },
          bluePrice: '',
          a: '', // 各级材料
          b: '', // 各级材料
          c: '', // 各级材料
          d: '', // 各级材料
          e: '', // 各级材料
        },
        show: false
      }
    },
    computed: {
      // 市场平均价格
      priceAverageRes() {
        let ret = []
        for (let key in this.form.priceAverage) {
          if (this.form.priceAverage[key] > 0) ret.push(this.form.priceAverage[key])
        }
        if (ret.length) {
          return Math.round(ret.reduce((pre, item) => pre + item) / ret.length)
        }
        return 0
      }
    },
    methods: {
      handleNewItem() {
        this.resetForm()
        this.show = true
      },
      // 立即创建
      onSubmit() {
        let data = { ...this.form }
        const { price, bluePrice, a, b, c, d, e, } = data
        data.material = Math.round(((a * mine.a) + (b * mine.b) + (c * mine.c) + (d * mine.d) + (e * mine.e)) / MINE_TRANSFER)
        data.cost = Math.round(bluePrice + data.material)
        data.averagePrice = this.priceAverageRes
        data.profit = Math.round(data.averagePrice - data.cost - (data.averagePrice * TAX))
        data.createTime = data.createTime ? data.createTime : new Date().getTime()
        data.updateTime = new Date().getTime()

        if (this.index) { // 如果是修改
          this.tableData.splice(this.index, data)
        } else {
          this.tableData.push(data)
        }
        this.show = false
        this.saveTableData()
        this.$notify({
          title: '成功',
          message: '新增成功',
          type: 'success',
          duration: 1500
        })
      },
      handleEdit(index, row) {
        this.form = row
        this.index = index // 当前修改的第几行
        this.show = true
      },
      handleDelete(index, row) {
        this.$confirm('确定删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.tableData.splice(index, 1)
          this.saveTableData()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 1500
          })
        })

      },
      saveTableData() {
        this.index = null
        window.localStorage.prices = JSON.stringify(this.tableData)
      },
      resetForm() {
        this.form = {
          level: 1,
          tLevel: 1,
          name: '',
          price: '',
          bluePrice: '',
          a: '',
          b: '',
          c: '',
          d: '',
          e: '',
          priceTop: '', // 市场最高价格
          priceBottom: '', // 市场最低价
          priceAverage: { // 市场平均价格
            a: '',
            b: '',
            c: ''
          }
        }
      },
      bindEnter() {
        if (this.bindEntered) return
        this.bindEntered = true
        this.$nextTick(() => {
          const form = this.$refs.form.$el
          const inputs = form.getElementsByTagName('input')
          inputs.forEach(el => {
            el.addEventListener('keyup', e => {
              if (e.which === 13) {
                e.preventDefault()
                this.onSubmit()
                return false
              }
            })
          })
        })
      },
      bindShortCuts() {
        document.onkeydown = (e) => {
          let keyCode = e.which
          let ctrlKey = e.ctrlKey
          if (ctrlKey && keyCode === 69) { // n键是系统新建窗口，无法覆盖
            e.preventDefault()
            this.handleNewItem()
            return false
          }
        }
      },
      handleMockData() {
        this.form = {
          name: 't',
          priceTop: 2342342, // 市场最高价格
          priceBottom: 2134, // 市场最低价
          priceAverage: { // 市场平均价格
            a: 12,
            b: 4,
            c: 8
          },
          bluePrice: 234,
          a: 12, // 各级材料
          b: 4, // 各级材料
          c: 25, // 各级材料
          d: 123, // 各级材料
          e: 234, // 各级材料
        }
      },
      bindClip() {
        let clipboard = new Clipboard('.btn')
        clipboard.on('success', (e) => {
          this.$message.success('复制成功')
        });
      }
    }
  }
</script>
